#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.oauth.general;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

/**
 * Description: 给所有调用auth模块的请求添加token
 *
 * @author songcx
 * @date 2019/8/26 10:09
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Configuration
public class AuthServerInterceptor implements RequestInterceptor {
    /**
     *header中验证信息名称
     */
    private static final String AUTHORIZATION_HEADER = "Authorization";
    /**
     *token类型
     */
    private static final String BEARER_TOKEN_TYPE = "Bearer";


    /**
     * Description:
     * <获取请求携带的token并添加到新的请求中去>
     * @author songcx
     * @date 11:47 2019/8/26
     * @param requestTemplate 1
     **/
    @Override
    public void apply(RequestTemplate requestTemplate) {

        // 获取security上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
            requestTemplate.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
        }
    }
}
